package com.countertack.vmware;

import java.io.File;
import java.sql.ResultSet;

import org.doublecloud.vi.vmware.guest.GuestProcessDirector;

import com.countertack.impala.ImpalaConnector;
import com.countertack.ssh.SSHManager;
import com.countertack.utils.Utils;
import com.vmware.vim25.GuestNicInfo;
import com.vmware.vim25.mo.VirtualMachine;

public class VMWareUtils {
	public static String getVMMacAddress(String esxiip, String vmname) {
		String macAdd = null;
		try {

			VMWareConnector esxiConnector = new VMWareConnector(esxiip);
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(vmname);
			esxiConnector.checkAndRunVirtualMachine(endPointMachine);
			GuestNicInfo[] gnetInfs = endPointMachine.getGuest().getNet();
			for (GuestNicInfo gnetInf : gnetInfs) {

				macAdd = gnetInf.getMacAddress();
				System.out.println("mac address>>>" + macAdd);

			}

			esxiConnector.closeEsxiConnection();

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			return macAdd;

		}

	}

	public static String performSmokeTerstOnVM(String esxiIp,
			String snapShotName, String vmName, String sentinelIp, String vmIp,
			String vmuser, String vmpassword, String kmLocation) {
		String behaviorId = null;
		String eId = null;
		ImpalaConnector iConnector = null;
		VMWareConnector esxiConnector = null;

		try {

			eId = installKM(esxiIp, snapShotName, vmName, sentinelIp, vmIp,
					vmuser, vmpassword, kmLocation);

			if (eId == null) {

				return null;
			}
			esxiConnector = new VMWareConnector(esxiIp);
			VirtualMachine vm = esxiConnector.getVirtualMachineByname(vmName);

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			// getting prodir connection
			boolean isXp = false;
			String osType = getVMOSArchitecture(esxiIp, vmName);
			if (vmName != null) {
				vmName = vmName.toLowerCase();
				if (vmName.contains("xp")) {

					isXp = true;
				}

			}
			GuestProcessDirector progDir = new GuestProcessDirector(vm, vmuser,
					vmpassword);

			if (isXp) {

				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe \"C:\\Documents and Settings\\"
								+ vmuser + "\\cmd.exe\"");

			} else {
				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe C:\\Users\\"
								+ vmuser + "\\cmd.exe");

			}

			Thread.sleep(60000);
			if (isXp) {
				progDir.run(
						"C:\\Documents and Settings\\" + vmuser + "\\cmd.exe",
						"/c ipconfig > \"c:\\Documents and Settings\\"
								+ vmuser
								+ "\\vmwaretest1.txt\" && sc query && arp -a && echo \"hello world\" >  \"c:\\Documents and Settings\\"
								+ vmuser
								+ "\\smoketestfile"

								+ ".txt\" && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_");

			} else {

				progDir.run(
						"C:\\Users\\" + vmuser + "\\cmd.exe",
						"/c ipconfig > c:\\Users\\"
								+ vmuser
								+ "\\vmwaretest1.txt && sc query && arp -a && echo \"hello world\" >  c:\\Users\\"
								+ vmuser
								+ "\\smoketestfile"

								+ ".txt && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_");

			}

			Thread.sleep(120000);

			ResultSet brs = iConnector
					.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
							+ eId
							+ "%'  order by event_start_time desc limit 1");

			while (brs.next()) {
				behaviorId = brs.getString(1);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			try {
				if (esxiConnector != null) {

					esxiConnector.closeEsxiConnection();
				}
			} catch (Exception e) {

			}
			return behaviorId;

		}

	}

	public static boolean runMalwareOnVirtualMachine(String esxiIp,
			String vmName, String vmIp, String vmuser, String vmpassword,
			String malwarePath) throws Exception {

		boolean isMalwareInstalled = true;
		VMWareConnector esxiConnector = null;
		SSHManager essh = null;
		try {

			File malwareFile = new File(malwarePath);
			if (!malwareFile.exists()) {

				System.out.println("No Malware File to install");
				return isMalwareInstalled;

			}

			esxiConnector = new VMWareConnector(esxiIp);

			VirtualMachine vm = esxiConnector.getVirtualMachineByname(vmName);

			esxiConnector.checkAndRunVirtualMachine(vm);
			if (vmIp == null || vmIp.trim() == "") {

				vmIp = vm.getGuest().ipAddress;

			}
			essh = new SSHManager(vmuser, vmpassword, vmIp);

			essh.connect();

			essh.copyFile(malwarePath, malwareFile.getName());

			Thread.sleep(60000);

			System.out.println("malware copied success fully");

			boolean isXp = false;
			String osType = getVMOSArchitecture(esxiIp, vmName);
			if (osType != null) {
				osType = osType.toLowerCase();
				if (osType.contains("xp")) {

					isXp = true;
				}

			}

			// installing malware

			if (isXp) {
				essh.runCommand("cmd /c \"c:\\Documents and Settings\\"
						+ vmuser + "\\" + malwareFile.getName() + "\" /quiet");

				System.out.println("malware installed success fully");

			} else {

				essh.runCommand("cmd /c \"C:\\Users\\" + vmuser + "\\"
						+ malwareFile.getName() + "\" /quiet");
				System.out.println("malware installed success fully");

			}

		} catch (Exception e) {

			isMalwareInstalled = false;
		}

		finally {

			try {

				if (esxiConnector != null) {

					esxiConnector.closeEsxiConnection();
				}
			} catch (Exception e) {

			}
			try {
				if (essh != null) {

					essh.closeSession();
					essh.doReconnect = false;

				}
			} catch (Exception e) {

			}
			return isMalwareInstalled;
		}

	}

	public static String performSmokeTerstOnVM(String sentinelIp,
			String vmuser, String vmpassword, String eId, VirtualMachine vm) {
		String behaviorId = null;

		ImpalaConnector iConnector = null;

		try {
			boolean isXp = false;

			if (vm != null) {

				try {
					String osType = vm.getConfig().getGuestFullName();

					if (osType != null) {

						osType = osType.toLowerCase();
						if (osType.contains("xp")) {

							isXp = true;
						}
					}
				} catch (Exception e) {

				}

			}

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			// getting prodir connection

			GuestProcessDirector progDir = new GuestProcessDirector(vm, vmuser,
					vmpassword);

			if (isXp) {
				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe \"C:\\Documents and Settings\\"
								+ vmuser + "\\cmd.exe\"");
			} else {
				progDir.run("C:\\Windows\\System32\\cmd.exe",
						"/c copy C:\\Windows\\System32\\cmd.exe C:\\Users\\"
								+ vmuser + "\\cmd.exe");

			}
			// Documents and Settings
			Thread.sleep(60000);
			if (isXp) {
				progDir.run(
						"C:\\Documents and Settings\\" + vmuser + "\\cmd.exe",
						"/c ipconfig > \"c:\\Documents and Settings\\"
								+ vmuser
								+ "\\vmwaretest1.txt\" && sc query && arp -a && echo \"hello world\" >  \"c:\\Documents and Settings\\"
								+ vmuser
								+ "\\smoketestfile"

								+ ".txt\" && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_");

			} else {

				progDir.run(
						"C:\\Users\\" + vmuser + "\\cmd.exe",
						"/c ipconfig > c:\\Users\\"
								+ vmuser
								+ "\\vmwaretest1.txt && sc query && arp -a && echo \"hello world\" >  c:\\Users\\"
								+ vmuser
								+ "\\smoketestfile"

								+ ".txt && reg  add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services\\smoketestkey_");
			}

			Thread.sleep(120000);

			ResultSet brs = iConnector
					.executeQueryAndReturnResults("select hex(id) from behaviors where uri like '%"
							+ eId
							+ "%'  order by event_start_time desc limit 1");

			while (brs.next()) {
				behaviorId = brs.getString(1);

			}

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			try {
				if (iConnector != null) {

					iConnector.closeImpalaConnection();
				}
			} catch (Exception e) {

			}

			return behaviorId;

		}

	}

	public static String installKM(String esxiIp, String snapShotName,
			String vmName, String sentinelIp, String vmIp, String vmuser,
			String vmpassword, String kmLocation) {
		String endpointId = null;
		SSHManager essh = null;
		VMWareConnector esxiConnector = null;

		ImpalaConnector iConnector = null;
		try {
			File kmFile = new File(kmLocation);
			if (!kmFile.exists()) {

				System.out.println("No KM File to install");
				return null;

			}
			esxiConnector = new VMWareConnector(esxiIp);
			VirtualMachine vm = esxiConnector.getVirtualMachineByname(vmName);

			if (snapShotName != null) {
				esxiConnector.revertToSnapShort(vm.getSnapshot()
						.getRootSnapshotList(), snapShotName);

			}

			esxiConnector.checkAndRunVirtualMachine(vm);
			if (vmIp == null || vmIp.trim() == "") {

				vmIp = vm.getGuest().ipAddress;

			}

			essh = new SSHManager(vmuser, vmpassword, vmIp);

			essh.connect();

			essh.copyFile(kmLocation, kmFile.getName());

			boolean isXp = false;
			String osType = getVMOSArchitecture(esxiIp, vmName);
			if (osType != null) {
				osType = osType.toLowerCase();
				if (osType.contains("xp")) {

					isXp = true;
				}

			}

			if (isXp) {

				essh.runCommand("cmd /c \"C:\\Documents and Settings\\"
						+ vmuser + "\\" + kmFile.getName() + "\" /S /HOST:"
						+ sentinelIp + " /PORT:443");

			} else {
				essh.runCommand("cmd /c \"C:\\Users\\" + vmuser + "\\"
						+ kmFile.getName() + "\" /S /HOST:" + sentinelIp
						+ " /PORT:443");

			}

			System.out.println("Installing agent on endpoint");
			Thread.sleep(120000);

			iConnector = new ImpalaConnector();
			iConnector.createImpalaConnection(sentinelIp);

			endpointId = Utils.getEndpointId(iConnector, vmIp);

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			if (essh != null) {

				try {
					essh.closeSession();
					essh.doReconnect = false;
				} catch (Exception e) {

				}

			}

			if (iConnector != null) {
				try {
					iConnector.closeImpalaConnection();
				} catch (Exception e) {

				}

			}

			if (esxiConnector != null) {
				try {
					esxiConnector.closeEsxiConnection();
				} catch (Exception e) {

				}
			}
			return endpointId;
		}

	}

	public static String getVMDomainName(String esxiip, String vmname) {

		String domName = null;
		try {

			VMWareConnector esxiConnector = new VMWareConnector(esxiip);
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(vmname);
			esxiConnector.checkAndRunVirtualMachine(endPointMachine);
			GuestNicInfo[] gnetInfs = endPointMachine.getGuest().getNet();
			for (GuestNicInfo gnetInf : gnetInfs) {

				domName = gnetInf.dnsConfig.domainName;
				System.out.println("Domainname >>>" + domName);

			}

			esxiConnector.closeEsxiConnection();

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			return domName;

		}
	}

	public static String getVMHostName(String esxiip, String vmname) {

		String hostName = null;
		try {

			VMWareConnector esxiConnector = new VMWareConnector(esxiip);
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(vmname);
			esxiConnector.checkAndRunVirtualMachine(endPointMachine);

			hostName = endPointMachine.getGuest().hostName;
			esxiConnector.closeEsxiConnection();

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			return hostName;

		}
	}

	public static String getVMRamSize(String esxiip, String vmname) {
		String ramSize = null;
		try {

			VMWareConnector esxiConnector = new VMWareConnector(esxiip);
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(vmname);

			ramSize = String
					.valueOf(endPointMachine.getConfig().hardware.memoryMB);
			esxiConnector.closeEsxiConnection();
		} catch (Exception e) {

			e.printStackTrace();
		} finally {

			return ramSize;
		}

	}

	public static String getVMOSArchitecture(String esxiip, String vmname) {
		String osArchitecture = null;
		try {
			VMWareConnector esxiConnector = new VMWareConnector(esxiip);
			// poweredOn
			VirtualMachine endPointMachine = esxiConnector
					.getVirtualMachineByname(vmname);

			osArchitecture = endPointMachine.getConfig().getGuestFullName();
			esxiConnector.closeEsxiConnection();

		} catch (Exception e) {

			e.printStackTrace();
		} finally {
			return osArchitecture;

		}

	}

}
